<?php

namespace services\clinic;

use common\models\clinic\UserSurplus;
use Yii;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\clinic\Project;
use common\models\clinic\ProjectBind;
use common\models\clinic\TreatmentRoom;
use api\modules\v1\forms\clinic\ProjectForm;
use yii\db\Expression;

/**
 * Class ProjectService
 * @package services\clinic
 */
class ProjectService extends Service
{
    /**
     * 根据ID查找治疗项目信息
     *
     * @param int $id
     * @return Project|null
     */
    public function findById(int $id = 0): ?Project
    {
        return Project::find()->where(['id' => $id])->one();
    }

    /**
     * 查找治疗项目信息
     *
     * @param array $condition
     * @return Project|null
     */
    public function findInfo(array $condition = []): ?Project
    {
        $query = Project::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找治疗项目列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Project::find();
        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['id']) && $query->andWhere(['id' => $condition['id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);
        isset($condition['template']) && $query->andWhere(['template' => $condition['template']]);

        // indexBy
        isset($condition['indexBy']) && $query->indexBy($condition['indexBy']);

        return $query->asArray()->all();
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function findListFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'status' => $row['status'],
            ];
        }

        return $list;
    }

    /**
     * 治疗项目列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = Project::find()->select(['a.*', 'GROUP_CONCAT(c.name) AS room_names'])->alias('a')
            ->leftJoin(ProjectBind::tableName() . ' AS b', 'b.clinic_project_id = a.id')
            ->leftJoin(TreatmentRoom::tableName() . ' AS c', 'c.id = b.treatment_room_id')
            ->where([
                'a.status' => [Project::STATUS_INVALID, Project::STATUS_ENABLE],
                'a.project_id' => $params['project_id'],
            ])
            ->groupBy('a.id');

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['a.status' => SORT_DESC, 'a.sort' => SORT_ASC, 'a.updated_at' => SORT_DESC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'name' => $row['name'],
                'bind_yiyuan_name' => $row['bind_yiyuan_name'],
                'room_names' => $row['room_names'] ? $row['room_names'] : '',
                'status' => $row['status'],
                'status_str' => Project::$statuss[$row['status']],
                'template' => $row['template'],
                'template_str' => Project::$templates[$row['template']],
                'sort' => $row['sort'],
            ];
        }

        return $list;
    }

    /**
     * 新增治疗项目
     *
     * @param ProjectForm $model
     * @return array|mixed
     */
    public function create(ProjectForm $model)
    {
        try {
            // 1.新增治疗项目
            $role = new Project();
            $role->project_id = $model->project_id;
            $role->name = $model->name;
            $role->bind_yiyuan_name = $model->bind_yiyuan_name;
            $role->status = $model->status;
            $role->template = $model->template;
            $role->sort = $model->sort;
            $role->save();

            return ['id' => $role->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑治疗项目
     *
     * @param ProjectForm $model
     * @return array|mixed
     */
    public function edit(ProjectForm $model)
    {
        try {
            // 1.更新治疗项目
            $attributes = [
                'name' => $model->name,
                'bind_yiyuan_name' => $model->bind_yiyuan_name,
                'status' => $model->status,
                'template' => $model->template,
                'sort' => $model->sort,
            ];
            Project::updateAll($attributes, ['id' => $model->id]);
            // 更新剩余量表冗余字段
            UserSurplus::updateAll(['clinic_project_name' => $model->name],['clinic_project_id' => $model->id]);


            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 删除治疗项目
     *
     * @param ProjectForm $model
     * @return array|mixed
     */
    public function delete(ProjectForm $model)
    {
        try {
            // 1.更新角色
            $attributes = [
                'status' => Project::STATUS_DELETE,
            ];
            Project::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑治疗项目状态
     *
     * @param ProjectForm $model
     * @return array|mixed
     */
    public function editStatus(ProjectForm $model)
    {
        try {
            // 1.更新角色
            $attributes = [
                'status' => $model->status,
            ];
            Project::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 获取最新的排序
     *
     * @param $projectId
     * @return int|mixed
     */
    public function getMaxSort($projectId)
    {
        $projectSort = Project::find()
            ->select([new expression("MAX(sort) as sort")])
            ->where(['project_id' => $projectId])
            ->limit(1)
            ->asArray()
            ->one();
        if ($projectSort) {
            return $projectSort['sort'] + 1;
        }
        return 1;

    }

}
